package com.dkm.dkmproject.utils.WechatGongutils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * request response封装
 * @version 2016/06/09
 *
 */
public class WebUtils{
    // 从session里取值

    public static Object getSessionAttribute(HttpServletRequest request, String name)
    {
        HttpSession session = request.getSession(false);
        return ((session != null) ? session.getAttribute(name) : null);
    }
    // 把值放入session
    public static void removeSessionAttribute(HttpServletRequest request, String name)
    {
        request.getSession().removeAttribute(name);
    }
    // 把值放入session
    public static void clearSessionAttribute(HttpServletRequest request)
    {
        request.getSession().invalidate();
    }
    // 把值放入session
    public static void setSessionAttribute(HttpServletRequest request, String name, Object value)
    {
        if (value != null) {
            request.getSession().setAttribute(name, value);
        }
        else {
            HttpSession session = request.getSession(false);
            if (session != null)
                session.removeAttribute(name);
        }
    }

    /**
     * 操作成功时给页面发出提示信息(ajax)
     * @param mes 消息
     * @param response
     * @throws IOException
     */
    public static void toPageJsonSuccess(String mes , HttpServletResponse response){
        try {
            WebUtils.toPageJsonMessage(1, mes, response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 操作错误时给页面发出提示信息(ajax)
     * @param mes 消息
     * @param response
     * @throws IOException
     */
    public static void toPageJsonFailed(String mes , HttpServletResponse response){
        try {
            WebUtils.toPageJsonMessage(-1, mes, response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 未登录
     * @param mes 消息
     * @param response
     * @throws IOException
     */
    public static void toPageJsonNoLogin(String mes , HttpServletResponse response){
        try {
            WebUtils.toPageJsonMessage(98, mes, response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 无权限
     * @param mes 消息
     * @param response
     * @throws IOException
     */
    public static void toPageJsonNoAuth(String mes , HttpServletResponse response){
        try {
            WebUtils.toPageJsonMessage(99, mes, response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 未登录
     * @param result 1成功 其他失败
     * @param mes 消息
     * @param response
     * @throws IOException
     */
    public static void toPageJsonMessage(int result , String mes , HttpServletResponse response) throws IOException{
        StringBuffer sb = new StringBuffer();
        sb.append("{");
        sb.append("\"result\":\""+result+"\",");
        sb.append("\"mes\":\""+mes+"\"");
        sb.append("}");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = response.getWriter();
        out.write(sb.toString());
        out.flush();
        out.close();
    }


    //向前台输出
    public static void toPageJson(HttpServletResponse response,String message){
        try {
            response.setContentType("application/json; charset=utf-8");//
            PrintWriter out = response.getWriter();
            out.print(message);
            out.flush();
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    //向前台输出
    public static void toPageXml(HttpServletResponse response,String message){
        try {
            response.setContentType("application/xml; charset=utf-8");//
            PrintWriter out = response.getWriter();
            out.print(message);
            out.flush();
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    //向前台输出
    public static void toPageText(HttpServletResponse response,String message){
        try {
            response.setContentType("text/html; charset=utf-8");//
            PrintWriter out = response.getWriter();
            out.print(message);
            out.flush();
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    //向前台输出
    public static void toPageTextPlain(HttpServletResponse response,String message){
        try {
            response.setContentType("text/plain; charset=utf-8");//
            PrintWriter out = response.getWriter();
            out.print(message);
            out.flush();
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public static String InputStreamToString(InputStream a){
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(a,"UTF-8"));
            line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
    //根据0和1 判断true和false
    public static boolean intToBoolean(int i)
    {
        return i==1?true:false;
    }
    /**
     * @Description: 获取服务器路径
     * @author cc
     * @param request
     * @return
     * @date 2015年6月10日
     */
    public static String getServerPath(HttpServletRequest request){
        String path = request.getContextPath();
        String basePath = request.getScheme()+"://"+request.getServerName();
        if(80!=request.getServerPort()){
            basePath+=":"+request.getServerPort();
        }
        basePath+=path;
        return basePath;
    }
    /**
     * 获取Cookies的值
     */
    public static String getCookies(HttpServletRequest request,String name){
        // 获取request里面的cookie cookie里面存值方式也是 键值对的方式
        String result="";
        Cookie[] cookie = request.getCookies();
        if(cookie==null) return "";
        for (int i = 0; i < cookie.length; i++) {
            Cookie cook = cookie[i];
            if(cook.getName().equals(name)){ //获取键
                result=cook.getValue().toString();
            }
        }
        return result;
    }
    public static String getRequestUrl(HttpServletRequest request){
        String url=WebUtils.getServerPath(request)+request.getServletPath();
        if(request.getQueryString()!=null){
            url += "?"+request.getQueryString();//完整url  加上参数
        }
        return url;
    }
    /**
     * 设置Cookies的值
     */
    public static void setCookies(HttpServletResponse response,String name,String value){
        Cookie cookie = new Cookie(name,value);
        cookie.setMaxAge(30*24*60*60);//设置1年有效期
        //设置路径，这个路径即该工程下都可以访问该cookie 如果不设置路径，那么只有设置该cookie路径及其子路径可以访问
        cookie.setPath("/");
        response.addCookie(cookie);
    }
    public static boolean isInApp(HttpServletRequest request){
        String referer=request.getHeader("referer");
        String from=request.getParameter("from");
        if(referer!=null&&from==null){
            return true;
        }else{
            return false;
        }
    }
    public static boolean isWeixin(HttpServletRequest request){
        String ua = request.getHeader("user-agent")
                .toLowerCase();
        if (ua.indexOf("micromessenger") > 0) {// 是微信浏览器
            return true;
        }else{
            return false;
        }
    }
}
 